package com.gzdh.tang.ali.rule;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.ali.model.OuterExtends;
import com.gzdh.tang.comm.constant.SpringContextUtils;
import com.gzdh.tang.comm.handler.IPayRuleHandler;
import com.gzdh.tang.comm.util.SnowFlake;
import com.gzdh.tang.config.weixin.WXEntity;
import com.gzdh.tang.config.weixin.WXPay;
import com.gzdh.tang.config.weixin.WXPayUtils;
import com.gzdh.tang.mobile.entity.Kl;
import com.gzdh.tang.mobile.service.KlService;
import com.gzdh.tang.modu.entity.*;
import com.gzdh.tang.modu.model.QrRestrictionsModel;
import com.gzdh.tang.modu.model.dk.JsonsRootBean;
import com.gzdh.tang.modu.service.*;
import com.gzdh.tang.modu.util.DateUtil;
import com.gzdh.tang.warehouse.service.DeviceService;
import com.gzdh.tang.warehouse.service.InStockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import com.gzdh.tang.config.ali.AliPayUtil;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 阿里默认支付实现类型，无折扣比例
 */
@Slf4j
public class AliBinHaiRule implements IPayRuleHandler {


    FkService fkService;

    GsService gsService;

    MacMainpSbruanService macMainpSbruanService;

    MacMainpSbruanDinnerService macMainpSbruanDinnerService;

    MacMainpSbruanKlService macMainpSbruanKlService;

    ReserveService reserveService;

    ReserveXfjTempService reserveXfjTempService;

    TangDeviceService tangDeviceService;

    DeviceService deviceService;

    InStockService inStockService;

    MacMainpSbruanKlDinnerService macMainpSbruanKlDinnerService;

    MacMainpSbruanKlButieService macMainpSbruanKlButieService;

    MacMainpSbruanOrdersService macMainpSbruanOrdersService;

    KlService klService;

    TangAddrService tangAddrService;

    AliCardAgreementService aliCardAgreementService;

    public AliBinHaiRule() {
        fkService = (FkService) SpringContextUtils.getBean("fkServiceImpl");
        gsService = (GsService) SpringContextUtils.getBean("gsService");
        macMainpSbruanService = (MacMainpSbruanService) SpringContextUtils.getBean("macMainpSbruanService");
        macMainpSbruanDinnerService = (MacMainpSbruanDinnerService) SpringContextUtils.getBean("macMainpSbruanDinnerService");
        macMainpSbruanKlService = (MacMainpSbruanKlService) SpringContextUtils.getBean("macMainpSbruanKlService");
        reserveService = (ReserveService) SpringContextUtils.getBean("reserveService");
        tangDeviceService = (TangDeviceService) SpringContextUtils.getBean("tangDeviceServiceImpl");
        deviceService = (DeviceService) SpringContextUtils.getBean("deviceServiceImpl");
        inStockService = (InStockService) SpringContextUtils.getBean("inStockService");
        macMainpSbruanKlDinnerService = (MacMainpSbruanKlDinnerService) SpringContextUtils.getBean("macMainpSbruanKlPriceService");
        macMainpSbruanKlButieService = (MacMainpSbruanKlButieService) SpringContextUtils.getBean("macMainpSbruanKlButieService");
        klService = (KlService) SpringContextUtils.getBean("klService");
        reserveXfjTempService = (ReserveXfjTempService) SpringContextUtils.getBean("reserveServiceXfjTemp");
        tangAddrService = (TangAddrService) SpringContextUtils.getBean("tangAddrServiceImpl");
        aliCardAgreementService = (AliCardAgreementService) SpringContextUtils.getBean("aliCardAgreementServiceImpl");
        macMainpSbruanOrdersService = (MacMainpSbruanOrdersService) SpringContextUtils.getBean("macMainpSbruanOrdersServiceImpl");
    }

    /**
     * 刷卡支付
     *
     * @param params
     * @return
     * @throws RuntimeException
     */
    @Override
    public JSONObject toCardPay(JSONObject params) throws RuntimeException {
        //缺省支付，默认插入到reserve即可操作
        String deviceId = params.getString("deviceId");
        String price = params.getString("price");
        String cardsn = params.getString("auth");
        String orders = params.getString("orders");
        int onLine = params.getInteger("onLine");
        String dateStr = params.getString("dateStr");
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(params);
        Date date = new Date();
        if (onLine > 0) {
            try {
                date = new SimpleDateFormat("yyyyMMddHHmmssSSS").parse(dateStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardsn, cardsn));
            if (fk == null) {
                throw new RuntimeException("非法卡");
            }
            Kl kl = klService.getOne(new QueryWrapper<Kl>().lambda().eq(Kl::getBm, fk.getKl()));
            if (kl != null && kl.getValid() == 1) {
                //判断有效期
                if (fk.getValiddate().compareTo(new Date()) < 0) {
                    throw new RuntimeException("超过有效期");
                }
            }
            jsonObject.put("fk", fk);
            Fk fk1 = reserveService.toCardPay2(deviceId, new BigDecimal(price).multiply(new BigDecimal(100)).intValue(), fk, orders, onLine, date);
            BigDecimal btye = new BigDecimal(fk.getBtye()).subtract(new BigDecimal(price));
//            fkService.lambdaUpdate().eq(Fk::getCardno, fk1.getCardno())
//                    .set(Fk::getBtye, fk1.getBtye())
//                    .set(Fk::getKye, fk1.getKye())
//                    .update();
            MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
            aliCardAgreementService.saveAgreement(fk1.getCardno(), price, macMainpSbruan.getAddr(), orders);
            jsonObject.put("fk", fk1);
            jsonObject.put("success", true);
            jsonObject.put("msg", "支付成功");
            jsonObject.put("userName", fk.getName());
            jsonObject.put("amount", price);
            List<OuterExtends> outerExtendsList = new ArrayList<>();
            outerExtendsList.add(addOutOuterExtends("姓名", fk.getName()));
            outerExtendsList.add(addOutOuterExtends("消费金额", price));
            outerExtendsList.add(addOutOuterExtends("卡余额", fk1.getKye()));
            outerExtendsList.add(addOutOuterExtends("补贴余额", fk1.getBtye()));
            jsonObject.put("outerExtends", outerExtendsList);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
        }
        return jsonObject;
    }

    private OuterExtends addOutOuterExtends(String name, String value) {
        OuterExtends outerExtends = new OuterExtends();
        outerExtends.setTitle(name);
        outerExtends.addDetail(name, value);
        return outerExtends;
    }

    /**
     * 现金支付
     *
     * @param params
     * @return
     * @throws RuntimeException
     */
    @Override
    public JSONObject toCashPay(JSONObject params) throws RuntimeException {
        return null;
    }

    /**
     * 二维码支付
     *
     * @param params
     * @return
     * @throws RuntimeException
     */
    @Override
    public JSONObject toQrPay(JSONObject params) throws RuntimeException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(params);
        //授权码，付款码或者电子饭卡
        String auth = params.getString("auth");
        int authType = 0;
        if (auth.length() < 19 && "1".equals(auth.substring(0, 1))) {
            //微信
            jsonObject.putAll(weixinQrPay(params));
        } else if (auth.length() < 19 && "2".equals(auth.substring(0, 1))) {
            //支付宝
            jsonObject.putAll(aliQrPay(params));
        } else {
            //其他，需要解码
            jsonObject.putAll(dzkPay(params));
        }
        return jsonObject;
    }

    /**
     * 刷脸支付
     * 先从FK表寻找是否存在人员，如果不存在，则返回查无此人，如果存在则正常往下校验
     * 注意地点： 不同地点使用不同的支付参数，利用机号获取到地点，再用地点表信息获取支付token
     * <p>
     * 发起支付是否涉及到超时问题，是否需要查单操作，优惠记录怎么处理，怎么编写
     * 先插入到一张临时表，利用临时表支付，支付成功编写到RESERVE表中，如果失败：利用调度中心进行查单操作
     *
     * @param params
     * @return
     * @throws RuntimeException
     */
    @Override
    public JSONObject toFacePay(JSONObject params) throws RuntimeException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String deviceId = params.getString("deviceId");
        String price = params.getString("price");
        String authCode = params.getString("faceToken");
        String orders = sdf.format(new Date()) + deviceId;
        String aliUid = params.getString("aliUid");
        String terminalParams = params.getString("terminal_params");
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(params);
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getAliUserId, aliUid));

        String enterprisePayAmount = "0.00";
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            String dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }

        try {
            Addr addr = tangAddrService.getOne(new QueryWrapper<Addr>().lambda().eq(Addr::getAddrNo, macMainpSbruan.getAddr()));

            if (fk == null) {
                throw new RuntimeException("查无此人");
            }
            if (StringUtils.isEmpty(fk.getAliEmployeeId())) {
                throw new RuntimeException("请先绑定企业");
            }

            Map<String, Object> resMap = reserveXfjTempService.toCardPay2(deviceId, new BigDecimal(price).multiply(new BigDecimal(100)).intValue(), fk, orders, 1, new Date(), null);

            Fk fk1 = (Fk) resMap.get("fk");
            enterprisePayAmount = resMap.get("amount").toString();
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(), "json", "GBK", AliPayUtil.getPublicKey(), "RSA2");
            AlipayTradePayRequest request = new AlipayTradePayRequest();
            JsonsRootBean jsonsRootBean = new JsonsRootBean(orders, price, authCode, AliPayUtil.getAssignJointAccountId(), enterprisePayAmount, terminalParams);
            request.setBizContent(JSONObject.toJSONString(jsonsRootBean));
            AlipayTradePayResponse response = alipayClient.execute(request, null, addr.getAliAppAuthToken());
            log.info(JSONObject.toJSONString(response));
            if (!response.isSuccess()) {
                throw new RuntimeException("支付失败");
            }
            List<OuterExtends> outerExtendsList = new ArrayList<>();
            outerExtendsList.add(addOutOuterExtends("姓名", fk.getName()));
            outerExtendsList.add(addOutOuterExtends("消费金额", price));
            if (response.getEnterprisePayInfo().getIsUseEnterprisePay()) {
                List<ReserveXfjTemp> reserveXfjTempList = reserveXfjTempService.list(new QueryWrapper<ReserveXfjTemp>().lambda().eq(ReserveXfjTemp::getLsh2, orders));
                List<Reserve> reserveList = new ArrayList<>();
                for (ReserveXfjTemp goo : reserveXfjTempList) {
                    Reserve reserve = new Reserve();
                    BeanUtils.copyProperties(goo, reserve);
                    reserveList.add(reserve);
                }
                reserveService.saveBatch(reserveList);
//                fkService.lambdaUpdate().set(Fk::getKye, fk1.getKye())
//                        .set(Fk::getBtye, fk1.getBtye())
//                        .eq(Fk::getCardno, fk1.getCardno())
//                        .update();
            } else {
                //未使用企业付，扣支付宝费用
                reserveService.insertReserve(deviceId, orders, new BigDecimal(price).multiply(new BigDecimal(100)).intValue(), 1, fk, macMainpSbruan, "现金菜", macMainpSbruan.getCode(), new BigDecimal(price), "4", orders, new Date());
            }
            outerExtendsList.add(addOutOuterExtends("卡余额", fk.getKye()));
            outerExtendsList.add(addOutOuterExtends("补贴余额", fk.getBtye()));
            jsonObject.put("fk", fk);
            jsonObject.put("success", true);
            jsonObject.put("msg", "支付成功");
            jsonObject.put("userName", fk.getName());
            jsonObject.put("amount", price);
            jsonObject.put("outerExtends", outerExtendsList);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
        }
        return jsonObject;
    }

    private String getDinner(MacMainpSbruan macMainpSbruan) throws Exception {
        String hourMin = new SimpleDateFormat("HH:mm").format(new Date());
        List<MacMainpSbruanDinner> macMainpSbruanDinnerList = macMainpSbruanDinnerService.list(new QueryWrapper<MacMainpSbruanDinner>().lambda().eq(MacMainpSbruanDinner::getDeviceId, macMainpSbruan.getId()));
        for (MacMainpSbruanDinner goo : macMainpSbruanDinnerList) {
            if (DateUtil.hourMinuteBetween(hourMin, goo.getStartTime(), goo.getEndTime())) {
                return goo.getDinner();
            }
        }
        throw new Exception("未找到该灶类");
    }

    //当游客消费，直接扣款
    public JSONObject weixinQrPay(JSONObject params) {

        JSONObject jsonObject = new JSONObject();
        BigDecimal price = new BigDecimal(params.getString("price")).multiply(new BigDecimal(100));

        String auth = params.getString("auth");
        String deviceId = params.getString("deviceId");
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            String dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }
        String orders = WXPayUtils.getPrefix() + SnowFlake.nextId() +  String.format("%04d", macMainpSbruan.getAddr());;
        String deviceOrders = params.getString("orders");
        jsonObject.put("success", false);
        jsonObject.put("msg", "正在支付中");
        QrRestrictionsModel qrRestrictionsModel = JSONObject.toJavaObject(JSONObject.parseObject(macMainpSbruan.getQrRestrictions()), QrRestrictionsModel.class);
        if (qrRestrictionsModel.getWxRestrictions() == 0) {
            jsonObject.put("success", false);
            jsonObject.put("msg", "当前模式尚未开通");
            return jsonObject;
        }
        if (StringUtils.isEmpty(macMainpSbruan.getCardno())) {
            jsonObject.put("success", false);
            jsonObject.put("msg", "系统尚未配置，支付失败");
            return jsonObject;
        }
        switch (qrRestrictionsModel.getWxRestrictions()) {
            case 1:
                jsonObject.put("success", false);
                jsonObject.put("msg", "当前【职工】模式尚未开通");
                break;
            case 2:
                jsonObject.put("success", false);
                jsonObject.put("msg", "当前【职工+游客】模式尚未开通");
                break;
            case 3:
                jsonObject.putAll(youkeWeixinPay(auth, price, orders, macMainpSbruan, deviceId, deviceOrders));
                break;
        }
        return jsonObject;
    }

    private JSONObject youkeWeixinPay(String auth, BigDecimal price, String orders, MacMainpSbruan macMainpSbruan, String deviceId, String deviceOrders) {
        WXEntity wxEntity = new WXEntity();
        JSONObject jsonObject = new JSONObject();
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, macMainpSbruan.getCardno()));
        if (fk == null) {
            jsonObject.put("success", false);
            jsonObject.put("msg", "CARDNO有误");
            return jsonObject;
        }
        MacMainpSbruanOrders macMainpSbruanOrders = new MacMainpSbruanOrders();
        macMainpSbruanOrders.setOrders(orders);
        macMainpSbruanOrders.setPrice(price.toPlainString());
        macMainpSbruanOrders.setDeviceOrder(deviceOrders);
        macMainpSbruanOrders.setType(1);//微信
        macMainpSbruanOrders.setCardno(macMainpSbruan.getCardno());
        macMainpSbruanOrdersService.save(macMainpSbruanOrders);

        try {
            reserveXfjTempService.insertReserve(deviceId, deviceOrders, price.intValue(), 1, fk,
                    macMainpSbruan, "现金菜", macMainpSbruan.getCode(), price, "3", orders, new Date(), null);
            Map<String, String> res = null;
            //region 向微信发起支付
            WXPay wxPay = new WXPay(wxEntity);
            Map<String, String> reqData = new HashMap<>();
            if (WXPayUtils.getSubmchMode() == 1) {
                //子商户模式
                reqData.put("sub_mch_id", WXPayUtils.getSubMchId());
            }
            reqData.put("body", "消费机");  //商品
            reqData.put("auth_code", auth);  //付款码
            reqData.put("spbill_create_ip", "8.8.8.8");//终端ip
            reqData.put("out_trade_no", orders);
            reqData.put("total_fee", price.stripTrailingZeros().toPlainString());
            res = wxPay.microPay(reqData, 10 * 1000, 10 * 1000);
            //endregion
            if ("SUCCESS".equals(res.get("return_code")) && "SUCCESS".equals(res.get("result_code"))) {
                //支付成功返回,需要保存记录
                macMainpSbruanOrdersService.paySuccessByDeviceOrders(deviceOrders);
                jsonObject.put("fk", fk);
                jsonObject.put("success", true);
                jsonObject.put("msg", "支付成功");
                jsonObject.put("userName", fk.getName());
                jsonObject.put("amount", price);
                jsonObject.put("resultCode", "SUCCESS");
            } else {
                jsonObject.put("success", true);
                jsonObject.put("resultCode", "QUERY");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
        }
        return jsonObject;
    }


    //支付宝二维码支付
    public JSONObject aliQrPay(JSONObject params) {
        JSONObject jsonObject = new JSONObject();
        String deviceId = params.getString("deviceId");
        String orders = params.getString("orders");
        String auth = params.getString("auth");
//        Map<String, String> res = ALiUtils.getAliUid(auth);
//        System.out.println(res.toString());
//        String aliUid = res.get("aliUid");
//        String senceNo = res.get("sence_no");
        String aliUid = "2088412156262616";
        String terminalParams = params.getString("terminal_params");
        String price = params.getString("price");
        jsonObject.put("success", false);
        jsonObject.put("msg", "请使用电子饭卡");
//        try{
//
//            String enterprisePayAmount = "0.00";
//            MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
//            try {
//                String dinner = getDinner(macMainpSbruan).trim();
//                macMainpSbruan.setDinner(dinner);
//            } catch (Exception e) {
//                e.printStackTrace();
//                throw new RuntimeException("餐次获取失败");
//            }
//            Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getAliUserId, aliUid));
//            if (fk == null) {
//                throw new RuntimeException("查无此人");
//            }
//            fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, fk.getCardno()));
//            jsonObject.put("fk", fk);
//
//            if (new BigDecimal(fk.getBtye()).compareTo(new BigDecimal(price)) >= 0 ||
//                    new BigDecimal(fk.getKye()).compareTo(new BigDecimal(price)) >= 0) {
//                enterprisePayAmount = price;
//            }
//            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
//                    AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(),
//                    "json", "GBK", AliPayUtil.getPublicKey(),
//                    "RSA2");
//            AlipayTradePayRequest request = new AlipayTradePayRequest();
//            JsonsRootBean jsonsRootBean = new JsonsRootBean(orders, price,
//                    auth, AliPayUtil.getAssignJointAccountId(), enterprisePayAmount, terminalParams);
//
//            request.setBizContent(JSONObject.toJSONString(jsonsRootBean));
//            AlipayTradePayResponse response = alipayClient.execute(request, null, AliPayUtil.getAppAuthToken());
//            log.info(JSONObject.toJSONString(response));
//            if (!response.isSuccess()) {
//                throw new RuntimeException("支付失败");
//            }
//            List<OuterExtends> outerExtendsList = new ArrayList<>();
//            outerExtendsList.add(addOutOuterExtends("姓名", fk.getName()));
//            outerExtendsList.add(addOutOuterExtends("消费金额", price));
//            if (response.getEnterprisePayInfo().getIsUseEnterprisePay()) {
//                //使用了企业付
//                //fundBillList
//                String sc = reserveService.toCardPay(deviceId, new BigDecimal(price).multiply(new BigDecimal(100)).intValue(), fk, orders);
//                if ("1".equals(sc)) {
//                    BigDecimal btye = new BigDecimal(fk.getBtye()).subtract(new BigDecimal(price));
//                    fkService.lambdaUpdate().eq(Fk::getCardno, fk.getCardno())
//                            .set(Fk::getBtye, btye.toPlainString())
//                            .update();
//                    fk.setBtye(btye.toPlainString());
//                } else if ("0".equals(sc)) {
//                    BigDecimal kye = new BigDecimal(fk.getKye()).subtract(new BigDecimal(price));
//                    fkService.lambdaUpdate().eq(Fk::getCardno, fk.getCardno())
//                            .set(Fk::getKye, kye.toPlainString())
//                            .update();
//                    fk.setKye(kye.toPlainString());
//                }
//            }else {
//                //未使用企业付，扣支付宝费用
//                reserveService.insertReserve(deviceId, orders,
//                        new BigDecimal(price).multiply(new BigDecimal(100)).intValue(), 1, fk, macMainpSbruan, "现金菜", macMainpSbruan.getCode(),
//                        new BigDecimal(price), "4", orders);
//            }
//            outerExtendsList.add(addOutOuterExtends("卡余额", fk.getKye()));
//            outerExtendsList.add(addOutOuterExtends("补贴余额", fk.getBtye()));
//            jsonObject.put("fk", fk);
//            jsonObject.put("success", true);
//            jsonObject.put("msg", "支付成功");
//            jsonObject.put("userName", fk.getName());
//            jsonObject.put("amount", price);
//            jsonObject.put("outerExtends", outerExtendsList);
//        }catch (Exception e){
//            jsonObject.put("success", false);
//            jsonObject.put("msg", e.getMessage());
//        }
        return jsonObject;
    }


    public JSONObject dzkPay(JSONObject params) {
        JSONObject jsonObject = new JSONObject();
        String deviceId = params.getString("deviceId");
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        QrRestrictionsModel qrRestrictionsModel = JSONObject.toJavaObject(JSONObject.parseObject(macMainpSbruan.getQrRestrictions()), QrRestrictionsModel.class);
        Fk fk = null;
        switch (qrRestrictionsModel.getDzkRestrictions()) {
            case 0:
                jsonObject.put("success", false);
                jsonObject.put("msg", "当前模式尚未开通");
                return jsonObject;
            case 1:
                //使用BASE64解码方式
                String authStr = params.getString("auth");
                byte[] bytes = Base64.getDecoder().decode(authStr);
                String json = new String(bytes);
                try {
                    String cardno = json.split(",")[0].split("=")[1];
                    String dates = json.split(",")[2].split("=")[1];
                    String nowDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis() - (2 * (60 * 1000) * 60)));
                    if (new BigDecimal(nowDate).compareTo(new BigDecimal(dates)) > 0) {
                        throw new RuntimeException("二维码已过期");
                    }
                    QueryWrapper<Fk> queryWrapper = new QueryWrapper<>();
                    queryWrapper.select("cardno,kh,bqh,ksh,id,name,cardsn,fkrq,kl,kye,btye,validdate,sfbm,openid,btcs");
                    queryWrapper.eq("cardNo", cardno);
                    fk = fkService.getOne(queryWrapper);
                } catch (Exception e) {
                    jsonObject.put("success", false);
                    jsonObject.put("msg", e.getMessage());
                    return jsonObject;
                }
                break;
            case 2:
                //通过数据库读取，获取一次解码
                fk = fkService.getFkByQr2(params.getString("auth"));
                break;
        }
        String price = params.getString("price");
        String orders = params.getString("orders");
        jsonObject.putAll(params);
        try {
            if (fk == null) {
                throw new RuntimeException("非法卡");
            }
            Kl kl = klService.getOne(new QueryWrapper<Kl>().lambda().eq(Kl::getBm, fk.getKl()));
            if (kl != null && kl.getValid() == 1) {
                //判断有效期
                if (fk.getValiddate().compareTo(new Date()) < 0) {
                    throw new RuntimeException("超过有效期");
                }
            }
            jsonObject.put("fk", fk);
            reserveService.toPayByYouXin(deviceId, new BigDecimal(price).multiply(new BigDecimal(100)).intValue(), fk, orders, 0, new Date());
            jsonObject.put("fk", fk);
            jsonObject.put("success", true);
            jsonObject.put("msg", "支付成功");
            jsonObject.put("userName", fk.getName());
            jsonObject.put("amount", price);
            jsonObject.put("resultCode", "SUCCESS");
            List<OuterExtends> outerExtendsList = new ArrayList<>();
            outerExtendsList.add(addOutOuterExtends("姓名", fk.getName()));
            outerExtendsList.add(addOutOuterExtends("消费金额", price));
            outerExtendsList.add(addOutOuterExtends("卡余额", fk.getKye()));
            outerExtendsList.add(addOutOuterExtends("补贴余额", fk.getBtye()));
            jsonObject.put("outerExtends", outerExtendsList);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
        }
        return jsonObject;
    }
}
